(function(window) {
	var ua = navigator.userAgent;

	function isAndroid() {
		return ua.indexOf("Android") > 0;
	}

	function isIOS() {
		return /(iPhone|iPad|iPod)/i.test(ua);
	}
	//是否开启日志
	window.webBridgeLoging=false;//默认为false
	/**
	 * 自定义包装日志方便关闭显示
	 */
	var logger={
			log :function(log){
				window.webBridgeLoging&&console.log(log);
			},
			info :function(log){
				window.webBridgeLoging&&console.info(log);
			},
			debug:function(log){
				window.webBridgeLoging&&console.debug(log);
			},
			warn:function(log){
				window.webBridgeLoging&&console.warn(log);
			},
			error:function(log){
				window.webBridgeLoging&&console.error(log);
			},
		}
	/**
	 * ios专用初始化函数
	 * @param {Object} initFunc
	 */
	function setupWebViewJavascriptBridge(initFunc) {
		if (window.WebViewJavascriptBridge) {
			return initFunc(WebViewJavascriptBridge);
		}
		if (window.WVJBCallbacks) {
			return window.WVJBCallbacks.push(initFunc);
		}
		window.WVJBCallbacks = [initFunc];
		var WVJBIframe = document.createElement("iframe");
		WVJBIframe.style.display = "none";
		WVJBIframe.src = "https://__bridge_loaded__";
		document.documentElement.appendChild(WVJBIframe);
		setTimeout(function() {
			document.documentElement.removeChild(WVJBIframe);
		}, 0);
	}
	/**
	 *通过bridge调用app端的方法
	 * @param method
	 * @param params
	 * @param callback
	 */
	function callAppRouter(method, params, callbackFun) {
		logger.debug('callAppRouter method='+method);
		logger.debug('callAppRouter params='+JSON.stringify(params));
		logger.debug('callAppRouter callbackFun='+callbackFun);
		try{
			if (isIOS()) {
				//生成回调函数方法名称	
				setupWebViewJavascriptBridge(function(bridge) {
					/* Initialize your app here */
					bridge.callHandler(method, params, function(cbData){
						logger.info('callAppRouter callback result='+JSON.stringify(cbData));
						callbackFun&&callbackFun(cbData);
					});
				});
			} else if (isAndroid()) {
				//生成回调函数方法名称
				var cbName =
					"CB_" + Date.now() + "_" + Math.ceil(Math.random() * 10);
				//挂载一个临时函数到window变量上，方便app回调
				window[cbName] = function(cbData) {
					logger.info('callAppRouter callback result='+JSON.stringify(cbData));
					callback(cbData);
					//回调成功之后删除挂载到window上的临时函数
					delete window[cbName];
				};
				var req = {
					method: method,
					data: params,
					callbackName: cbName
				};
				bridge.callHandler(JSON.stringify(req));
			}
		}catch(e){
			logger.error(e);
		}
	}
	//原生调用能力添加到mobile下
	var mobile = {
		scanQrcode: function(callback) {
			logger.log('scanQrcode init...');
			callAppRouter("scanQrcode", {}, callback);
		}
	};
	//将mobile对象挂载到window全局
	window.webBridge = mobile;
})(window);
